const ManagedModel = require('../models/ManagedModel.js');

// 获取所有模型（分页）
const getModels = async (ctx) => {
  try {
    const page = parseInt(ctx.query.page) || 1;
    const pageSize = parseInt(ctx.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;

    const { count, rows } = await ManagedModel.findAndCountAll({
      offset: offset,
      limit: pageSize,
    });

    ctx.body = {
      code: 200,
      data: {
        total: count,
        records: rows,
      },
      message: 'Success',
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { code: 500, message: error.message };
  }
};

// 根据ID获取模型
const getModelById = async (ctx) => {
  try {
    const model = await ManagedModel.findByPk(ctx.params.id);
    if (model) {
      ctx.body = {
        code: 200,
        data: model,
        message: 'Success',
      };
    } else {
      ctx.status = 404;
      ctx.body = { code: 404, message: 'Model not found' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { code: 500, message: error.message };
  }
};

// 创建新模型
const createModel = async (ctx) => {
  try {
    const model = await ManagedModel.create(ctx.request.body);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      data: model,
      message: 'Model created successfully',
    };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { code: 400, message: error.message };
  }
};

// 更新模型
const updateModel = async (ctx) => {
  try {
    const [updated] = await ManagedModel.update(ctx.request.body, {
      where: { id: ctx.params.id },
    });
    if (updated) {
      const updatedModel = await ManagedModel.findByPk(ctx.params.id);
      ctx.body = {
        code: 200,
        data: updatedModel,
        message: 'Model updated successfully',
      };
    } else {
      ctx.status = 404;
      ctx.body = { code: 404, message: 'Model not found' };
    }
  } catch (error) {
    ctx.status = 400;
    ctx.body = { code: 400, message: error.message };
  }
};

// 删除模型
const deleteModel = async (ctx) => {
  try {
    const deleted = await ManagedModel.destroy({
      where: { id: ctx.params.id },
    });
    if (deleted) {
        ctx.body = {
        code: 200,
        message: 'Model deleted successfully',
      };
    } else {
      ctx.status = 404;
      ctx.body = { code: 404, message: 'Model not found' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { code: 500, message: error.message };
  }
};

module.exports = {
  getModels,
  getModelById,
  createModel,
  updateModel,
  deleteModel
};